#include "player.h"

player::player(void)
{

}
player::player(LPDIRECT3DTEXTURE9 img, LPDIRECT3DDEVICE9 dev, int type, int x, int y, int w, int h, int speed)
{
	this->img = img;
	this->result = D3DXCreateSprite(dev, &(this->handler));
	this->d3ddev = dev;
	//load image resources
	this->trung = LoadTexture("resource/images/character/egg.png", D3DCOLOR_XRGB(255,0,255));
	this->chatthai = LoadTexture("resource/images/character/shit.png", D3DCOLOR_XRGB(255,0,255));
	/*     *  	 */
	this->start = (int) rand() % 100;
	this->t = 0;
	this->type = type;
	this->already = false;
	this->x = x;
	this->y = y;
	this->w = w;
	this->h = h;
	this->speed = speed;
	this->sprite.x = x;
	this->sprite.y = y;
	this->sprite.width = w;
	this->sprite.height = h;
	this->sprite.movex = speed;
}
void player::draw() 
{
	handler->Begin(D3DXSPRITE_ALPHABLEND);
	//create vector to update sprite position
	D3DXVECTOR3 position((float)this->sprite.x, (float)this->sprite.y, 0);
	//draw the sprite
	handler->Draw(
		this->img, 
		NULL,
		NULL,
		&position,
		D3DCOLOR_XRGB(255,255,255));
	//stop drawing
	handler->End();
	for (int i = 0;i < _sanpham.size();i++) 
	{
		_sanpham[i]->draw();
	}
}
void player::update(CRo* ro, int &point, int &eggs, int &shits, int &broken_eggs)
{
	//move
	this->sprite.x += this->sprite.movex;
	if (this->sprite.x >= 640 - this->sprite.width || 
		this->sprite.x <= 0) {
		this->sprite.movex = -this->sprite.movex;
	}
	//check
	for (int i = 0;i < _sanpham.size();i++)
	{
		if (_sanpham[i]->checkLifeTime()) {
			if ( _sanpham[i]->getType() == 0 ) {
				broken_eggs++;
			}
			_sanpham.erase(_sanpham.begin() + i);				
		}else if (_sanpham[i]->checkCollision(ro)) {
			//0: egg; 1: shit;
			switch (_sanpham[i]->getType()) {
				case 1:
					shits++;
					point += point > 0 ? -1 : 0; 
					break;
				case 0:
					point++;
					eggs++;
					break;
			}
			//delete product
			_sanpham.erase(_sanpham.begin() + i);
		}else{
			//update product
			_sanpham[i]->update();
		}
	}

}
void player::setSpeed(int val) {
	for (int i = 0;i < _sanpham.size();i++)
	{
		_sanpham[i]->setSpeed(val);
	}
}
void player::deTrung()
{	
	if ( !already ) {
		if (t < start) {
			t++;
		}else{
			t = 0;
			already = true;
		}
	}
	if ( already ) {
		t += CLOCKS_PER_SEC;
		if ( t % ( 5 * CLOCKS_PER_SEC * 30 ) == 0 ) { //25 tick per second
			t = 0;
			int rand_t = rand() % 2;
			switch (rand_t) {
				case 0:
					_sanpham.push_back(new CSanPham(trung, d3ddev, rand_t, this->sprite.x, this->sprite.y
						,25, 30, 3));
					break;
				case 1:
					_sanpham.push_back(new CSanPham(chatthai, d3ddev, rand_t, this->sprite.x, this->sprite.y
						,32, 33, 3));
					break;
			}
		}
	}
}
vector<CSanPham*> player::getProduct() 
{
	return this->_sanpham;
}
player::~player(void)
{
	img->Release();
	handler->Release();
	trung->Release();
	chatthai->Release();
}
